package com.yubest.demo.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @describe: 字符长度校验器，中文占两字符长度
 * @author: hweiyu
 * @date: 2020/12/9 17:04
 */
public class LengthValidator implements ConstraintValidator<Length, String> {

    private Length length;

    @Override
    public void initialize(Length constraintAnnotation) {
        this.length = constraintAnnotation;
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        int len = this.calLen(s);
        return len >= length.min() && len <= length.max();
    }

    private int calLen(String s) {
        if (null == s) {
            return 0;
        }
        //中文占两个字符长度
        return s.trim()
                .replaceAll("[^\\x00-\\xff]", "**")
                .length();
    }

}
